﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WeiTap.Web;

namespace BrnMall.Baidu.Sdk
{
    public static class MapApi
    {
        public static GeoLocation GetLocation(float latitude, float longitude)
        {
            try
            {
                var www = new HttpFire(string.Format(
                    "http://api.map.baidu.com/geocoder/v2/?location={0},{1}&output=json&pois=0&latest_admin=1&ak={2}",
                    latitude, longitude, Config.AK));
                www.Method = HttpRequestMethod.Get;
                var res = www.GetString();
                var geo = JsonConvert.DeserializeObject<GeoLocation>(res);
                return geo;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
            
        }
        /// <summary>
        /// 根据地址获取经纬度坐标
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static GeoLocation GetLocation(string address)
        {
            try
            {
                var www = new HttpFire(string.Format(
                    "http://api.map.baidu.com/geocoder/v2/?address={0}&output=json&ak={1}",
                    address, Config.AK));
                www.Method = HttpRequestMethod.Get;
                var res = www.GetString();
                var geo = JsonConvert.DeserializeObject<GeoLocation>(res);
                return geo;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 计算两点的距离
        /// </summary>
        /// <param name="lat1"></param>
        /// <param name="lng1"></param>
        /// <param name="lat2"></param>
        /// <param name="lng2"></param>
        /// <returns></returns>
        public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
        {
            try
            {
                double distance = 0;
                double lonRes = 102900, latRes = 110000;
                distance = Math.Sqrt(Math.Abs(lat1 - lat2) * latRes * Math.Abs(lat1 - lat2) * latRes +
                                     Math.Abs(lng1 - lng2) * lonRes * Math.Abs(lng1 - lng2) * lonRes);
                //System.out.println( "两点间距离:" + distance );
                return distance;
            }
            catch (Exception e)
            {
               Trace.TraceError(e.Message);
                throw;
            }
            
        }
    }
}
